import time
from decimal import Decimal
from json import JSONEncoder

import pyodbc
import requests
import json
from datetime import datetime

from logger import log
from settings import settings


class DecimalEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)  # or str(obj)
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, bytes):
            return bool(obj)
        return super().default(obj)


def fetch_data_from_sqlserver(connection_string, query):
    """
    从SQL Server数据库获取数据
    """
    try:
        # 建立数据库连接
        conn = pyodbc.connect(connection_string)
        cursor = conn.cursor()

        # 执行查询
        cursor.execute(query)

        # 获取列名
        columns = [column[0] for column in cursor.description]

        # 获取数据并转换为字典列表
        data = []
        for row in cursor.fetchall():
            row_data = {}
            for i, col in enumerate(columns):
                # 处理datetime对象，使其可JSON序列化
                if isinstance(row[i], datetime):
                    row_data[col] = row[i].isoformat()
                else:
                    row_data[col] = row[i]
            data.append(row_data)

        return data
    except Exception as e:
        log.error(f"从SQL Server获取数据时出错: {e}")
        return None
    finally:
        if 'conn' in locals():
            conn.close()


def send_data_to_server(api_url, data, headers=None):
    """
    通过POST请求发送数据到服务器
    """
    try:
        # 默认headers
        if headers is None:
            headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

        # 发送POST请求
        response = requests.post(
            api_url,
            data=json.dumps(data, ensure_ascii=False, cls=DecimalEncoder),
            headers=headers
        )

        # 检查响应
        if response.status_code == 200:
            return True
        else:
            log.error(f"服务器返回错误: {response.status_code}")
            log.error("响应内容:", response.text)
            return False
    except Exception as e:
        log.error(f"发送数据到服务器时出错: {e}")
        return False


def main():
    log.info("开始获取数据...")
    # 配置数据库连接
    server = '192.168.10.104'
    database = 'QLMWeight'
    username = 'hlsk'
    password = 'Hlsk@1234'
    driver = '{ODBC Driver 17 for SQL Server}'  # 根据你的ODBC驱动版本调整

    connection_string = f"""
        DRIVER={driver};
        SERVER={server};
        DATABASE={database};
        UID={username};
        PWD={password};
        TrustServerCertificate=yes;
    """

    # SQL查询
    query = """
SELECT TOP
  (10) [serialNo] as code,
  1648 as create_tenant_id,
  'Out' as state,
  'Out' as weight_state,
  'SM' as type,
  '山西富朔煤炭运销有限公司' as create_tenant_name,
  '山西富朔煤炭运销有限公司' as customer_name,
  [plateNo] as car_num,
  [goodsName] as product_name,
  [grossWeight] as gross_weight,
  [tareWeight] as tare_weight,
  [netWeight] as net_weight,
  [firstTime] as first_time,
  [secondTime] as second_time,
  [secondTime] as out_time,
  [remark] as remark
FROM
  [QLMWeight].[dbo].[tbl_weightInfo]
ORDER BY
  operateTime DESC
    """

    # API端点
    api_url = 'https://platform.wechain360.com/api/depatch/internal/dataBatchImport'

    try:
        while True:
            # 从SQL Server获取数据
            data = fetch_data_from_sqlserver(connection_string, query)

            if data:
                log.info(f"成功获取 {len(data)} 条记录")
                # print(data)
                postData = {
                    "list": data,
                    "platformId": settings.platformId,
                    "platformName": settings.platformName,
                    "modelCode": "bang_dan"
                }

                # 发送数据到服务器
                log.info(f"发送数据到服务器{postData}")
                send_data_to_server(api_url, postData)
            else:
                print("未能从数据库获取数据")
            time.sleep(30)  # 主线程保持运行
    except Exception as e:
        log.info(f"程序已终止。{e}")


if __name__ == "__main__":
    main()
